package psn.zjk.spring.dubbo.client;

import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import psn.zjk.spring.trace.entity.TraceInfo;
import psn.zjk.spring.utils.JacksonUtils;

import java.time.Instant;
import java.time.format.DateTimeFormatter;

/**
 * @author zhangjk
 * @Description
 * @CREATE_TIME 2021/6/22 11:20
 */
public class TraceClient implements Filter {
    private static final Logger logger= LoggerFactory.getLogger(TraceClient.class);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = MDC.get("traceId");
        Object[] arguments = invocation.getArguments();
        String methodName = invocation.getMethodName();
        invocation.setAttachment("traceId",traceId);
        Instant now = Instant.now();
        String start = formatter.format(now);

        Result result = invoker.invoke(invocation);

        Instant  now2 = Instant.now();
        TraceInfo traceInfo = new TraceInfo();
        traceInfo.setArgs(JacksonUtils.object2Json(arguments));
        traceInfo.setClazz(invocation.getServiceName());
        traceInfo.setMethod(methodName);
        traceInfo.setTraceId(traceId);
        traceInfo.setStart(start);
        traceInfo.setEnd(formatter.format(now2));
        traceInfo.setCost(now2.compareTo(now));
        traceInfo.setTarget(invoker.getUrl().getAddress());
        logger.info(traceInfo.toString());
        return result;
    }
}